import { _decorator, Color, Component, EventTouch, instantiate, Label, macro, Node, Prefab, tween, v3, Vec3 } from 'cc';
import { CollisionItem } from './CollisionItem';
import { LeaderboardItem } from './LeaderboardItem';
import { EventManager, MyEvent } from './EventManager';
const { ccclass, property } = _decorator;

@ccclass('CollisionManager')
export class CollisionManager extends Component {
    public static Instance: CollisionManager = null;

    @property(Prefab)
    CollisionPrefab: Prefab = null;

    @property
    R: number = 500;

    @property
    r: number = 15;

    @property(Node)
    LeaderboardItems: Node[] = [];

    @property
    Time: number = 9;

    @property(Label)
    Timer: Label = null;

    @property(Node)
    AredNode: Node = null;

    @property(Node)
    StartNode: Node = null;

    public IsStart: boolean = false;
    public CollisionItems: CollisionItem[] = [];

    time: number = 0;

    private _isPause: boolean = false;

    protected onLoad(): void {
        CollisionManager.Instance = this;

        this.AredNode.once(Node.EventType.TOUCH_START, this.onTouchStart, this);
        tween(this.StartNode)
            .to(1, { scale: v3(1.2, 1.2, 1.2) }, { easing: `sineIn` })
            .to(1, { scale: v3(1, 1, 1) }, { easing: `sineIn` })
            .union()
            .repeatForever()
            .start();
    }

    protected start(): void {
        this.init();
    }

    protected update(dt: number): void {
        if (this._isPause) return;
        this.showLeaderboardItem();
    }

    updateTimer() {
        console.error(1);

        if (this._isPause) return;
        if (this.time > 0) {
            this.time--;
            let color: Color = Color.WHITE;
            if (this.time <= 3) {
                color = Color.RED;
            }
            this.Timer.color = color;
            this.Timer.string = `下一次消除：${this.time}秒`;
        } else {
            this.unschedule(this.updateTimer);  // 停止计时器
            this.nextWave();
        }
    }

    startTimer() {
        this.time = this.Time;
        // 每秒钟更新一次计时器
        this.schedule(this.updateTimer, 1, macro.REPEAT_FOREVER, 0);
    }

    nextWave() {
        const collisionItem: CollisionItem = this.CollisionItems.pop();
        collisionItem.removeSelf();
        if (this.CollisionItems.length == 1) {
            //游戏结束
            this.Timer.color = Color.WHITE;
            this.Timer.string = `恭喜${this.CollisionItems[0].node.name}获得胜利！`;
            return;
        }
        this.startTimer();
    }

    init() {
        // 大圆圆心
        const center = new Vec3(0, 0, 0);

        // 从中心往外一层一层铺
        for (let k = 0; ; k++) {
            // 当前层半径
            const d = k * Math.sqrt(3) * this.r;

            if (d + this.r > this.R) break; // 超出大圆范围就停止

            if (k === 0) {
                // 中心点放一个小圆
                this.spawnCircle(center);
            } else {
                const num = 6 * k; // 本层小圆数
                for (let i = 0; i < num; i++) {
                    const angle = (2 * Math.PI * i) / num;
                    const x = center.x + d * Math.cos(angle);
                    const y = center.y + d * Math.sin(angle);
                    const pos = new Vec3(x, y, 0);

                    // 判断是否在大圆内
                    if (Vec3.distance(center, pos) + this.r <= this.R) {
                        this.spawnCircle(pos);
                    }
                }
            }
        }
    }

    showLeaderboardItem() {
        this.CollisionItems.sort((a, b) => b.Collisions.length - a.Collisions.length);
        for (let i = 0; i < this.LeaderboardItems.length; i++) {
            if (i >= this.CollisionItems.length) {
                this.LeaderboardItems[i].active = false;
                continue;
            }
            const leaderboardItem: LeaderboardItem = this.LeaderboardItems[i].getComponent(LeaderboardItem);
            leaderboardItem.init(this.CollisionItems[i].Color, this.CollisionItems[i].node.name, this.CollisionItems[i].Collisions.length.toString(), i == this.CollisionItems.length - 1);
        }
    }

    // 工具函数：生成小圆
    spawnCircle(pos: Vec3) {
        const circle = instantiate(this.CollisionPrefab);
        circle.setPosition(pos);
        this.node.addChild(circle);
    }

    private pause() {
        this._isPause = !this._isPause;
    }

    protected onEnable(): void {
        EventManager.on(MyEvent.PAUSE, this.pause, this);
    }

    protected onDisable(): void {
        EventManager.off(MyEvent.PAUSE, this.pause, this);
    }

    onTouchStart(event: EventTouch) {
        this.IsStart = true;
        this.AredNode.active = false;
        this.CollisionItems.forEach(e => e.applyRandomForce());
        this.startTimer();
    }
}


